package com.cjw.service.impl.soulread;

import com.cjw.mapper.soulread.TagMapper;
import com.cjw.mapper.soulread.TagReadMapper;
import com.cjw.pojo.dto.soulread.TagDTO;
import com.cjw.pojo.dto.soulread.TagListDTO;
import com.cjw.pojo.entity.soulread.Tag;
import com.cjw.pojo.entity.soulread.TagRead;
import com.cjw.service.soulread.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author : cjw
 * @date: : 2022/1/24 8:52
 * @description : TagServiceImpl
 */
@Service("tagService")
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private TagReadMapper tagReadMapper;

    @Override
    public List<TagDTO> getTagDTOByReadId(Long readId) {
        ArrayList<TagDTO> tagDTOList = new ArrayList<>();
        TagRead tagRead = new TagRead();
        tagRead.setReadId(readId);
        List<TagRead> tagReadList = tagReadMapper.select(tagRead);
        if (tagReadList == null || tagReadList.size() == 0)
            return null;
        for (TagRead tagRead1 : tagReadList) {
            Tag tag = new Tag();
            tag.setId(tagRead1.getTagId());
            Tag tag1 = tagMapper.selectOne(tag);
            TagDTO tagDTO = new TagDTO();
            tagDTO.setLabel(tag1.getName());
            tagDTO.setType(tag1.getType());
            tagDTOList.add(tagDTO);
        }
        return tagDTOList;
    }

    @Override
    public List<TagListDTO> getTagListDTO() {
        ArrayList<TagListDTO> tagListDTOS = new ArrayList<>();
        for (Tag tag : tagMapper.selectAll()) {
            TagListDTO tagListDTO = new TagListDTO();
            tagListDTO.setTagId(tag.getId());
            tagListDTO.setTagName(tag.getName());
            tagListDTOS.add(tagListDTO);
        }
        return tagListDTOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addTagRead(Long readId, String tagName, String tagType) {
        TagRead tagRead = new TagRead();
        tagRead.setReadId(readId);
        tagRead.setTagId(addTag(tagName,tagType));
        return tagReadMapper.insert(tagRead) == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addTag(String tagName, String tagType) {
        Tag tag = new Tag();
        tag.setName(tagName);
        // 如果tagName一样，就不进行插入新的标签
        Tag tag1 = tagMapper.selectOne(tag);
        if (tag1 != null)
            return tag1.getId();
        tag.setType(tagType);
        tag.setAddTime(new Date());
        tag.setUpdateTime(new Date());
        tag.setScore(1.0); // 这里是默认的，后面会通过后台修改
        return new Long(tagMapper.insertUseGeneratedKeys(tag));
    }


}
